import React, { useEffect, useState } from "react"
import { Drawer, Button, Table, InputNumber, Radio, Modal, Alert, Input, Tag } from "antd"

import SearchAutoComplete from "libs/search-auto-complete"

import { postJSON, get } from "../../shared/server"
import { plus } from "../../shared/libs/numberCacl"

import "./index.less"
import SendOutlined from "@ant-design/icons/lib/icons/SendOutlined"
import { read } from "zr-react-toolbox"
import cs from "classnames"
import LoadingOutlined from "@ant-design/icons/lib/icons/LoadingOutlined";

const TestDrawer = (props) => {
	const { visible, onClose } = props
	const [productList, setProductList] = useState([])
	const [sourceProductList, setSourceProductList] = useState([])
	const [selectedRowKeys, setSelectedRowKeys] = useState([])
	const [totalPrice, setTotalPrice] = useState(0)
	const [dealPrice, setDealPrice] = useState("")
	const [testResult, setTestResult] = useState(null)
	const [radioValue, setRadioValue] = useState("all")
	const [loading, setLoading] = useState(false)

	const loadTableData = (searchKey) => {
		get("/management/product/list", { searchKey: searchKey || "" }).then(result => {
			if (result) {
				setRadioValue("all")
				setProductList(result)
				setSourceProductList(result)
			}
		})
	}

	useEffect(() => {
		loadTableData()
	}, [])

	const onSelectChange = (record, selected) => {
		let selectedItems
		if (selected) {
			selectedItems = [...new Set([].concat(selectedRowKeys).concat(record.id))]
			setSelectedRowKeys(selectedItems)
		} else {
			selectedItems = selectedRowKeys.filter(item => item !== record.id)
			setSelectedRowKeys(selectedItems)
		}
		const selectedProducts = sourceProductList.filter(item => {
			if (selectedItems.includes(item.id)) {
				return item
			}
		})
		const priceTotal = selectedProducts.reduce((acc, current) => {
			return {
				marketPriceTotal: plus(parseFloat(acc.marketPriceTotal), parseFloat(current.marketPrice)),
				fixedCostPriceTotal: plus(parseFloat(acc.fixedCostPriceTotal), parseFloat(current.fixedCostPrice)),
				volatileCostPriceTotal: plus(parseFloat(acc.volatileCostPriceTotal), parseFloat(current.volatileCostPrice)),
				otherCostPriceTotal: plus(parseFloat(acc.otherCostPriceTotal), parseFloat(current.otherCostPrice)),
			}
		}, {
			marketPriceTotal: 0,
			fixedCostPriceTotal: 0,
			volatileCostPriceTotal: 0,
			otherCostPriceTotal: 0
		})
		setTotalPrice(priceTotal)
	}

	const onSubmit = () => {
		setLoading(true)
		postJSON("/management/config/evaluate", { dealPrice: dealPrice + "", ids: selectedRowKeys })
			.then(response => {
				if (response) {
					setTestResult(response)
				}
			}).finally(() => setLoading(false))
	}

	const columns = [
		{
			title: "项目编号",
			dataIndex: "itemNo",
			key: "itemNo"
		},
		{
			title: "名称",
			dataIndex: "name",
			key: "name"
		},
		{
			title: "简码",
			dataIndex: "briefCode",
			key: "briefCode"
		},
		{
			title: "固定成本价(元)",
			dataIndex: "fixedCostPrice",
			key: "fixedCostPrice",
			render: text => `￥${text}`
		},
		{
			title: "可变成本价(元)",
			dataIndex: "volatileCostPrice",
			key: "volatileCostPrice",
			render: text => `￥${text}`
		},
		{
			title: "其他成本价(元)",
			dataIndex: "otherCostPrice",
			key: "otherCostPrice",
			render: text => `￥${text}`
		},
		{
			title: "市场价(元)",
			dataIndex: "marketPrice",
			key: "marketPrice",
			render: text => `￥${text}`
		},
	]

	const rowSelection = {
		selectedRowKeys,
		onSelect: onSelectChange,
		hideSelectAll: true,
	}

	const handleClose = () => {
		setTestResult(null)
		setSelectedRowKeys([])
		setDealPrice("")
		setTotalPrice("")
		onClose()
	}

	const options = [
		{ label: '全部', value: 'all' },
		{ label: '已选中', value: 'selected' },
		{ label: '未选中', value: 'unselected' },
	]

	const handleChangeRadio = event => {
		const value = event.target.value
		setRadioValue(value)
		let tmp
		if (value === "all") {
			loadTableData()
			tmp = sourceProductList
		} else if (value === "selected") {
			tmp = sourceProductList.filter(item => selectedRowKeys.includes(item.id))
		} else {
			tmp = sourceProductList.filter(item => !selectedRowKeys.includes(item.id))
		}
		setProductList(tmp)
	}

	const isCanSubmit = selectedRowKeys && selectedRowKeys.length > 0 && dealPrice
	const score = read(testResult, "score")
	const passed = read(testResult, "passed")
	const levelName = read(testResult, "levelName")

	return (
		<Drawer
			className={'tester-drawer'}
			width={700}
			title="配置测试"
			placement="right"
			onClose={handleClose}
			visible={visible}
		>
			<div className="drawer-content">
				{
					loading ? <div className={'tester-alert-box'}><h3><LoadingOutlined />正在评估....</h3></div> : undefined
				}
				{
					testResult && !loading ? <div className={'tester-alert-box'}>
						<h1>{passed ? <span className={'passed'}>达标</span> : <span className={'not-passed'}>不达标</span>}</h1>
						<div>
							<Tag className='large' color={passed ? '#00a551' : '#f50'}>等级:{levelName}</Tag>
							<Tag className='large' color={passed ? '#00a551' : '#f50'}>分数:{score}</Tag>
						</div>
					</div>
						: undefined
				}
				<div className="search-box">
					<SearchAutoComplete allowClear={true} onSelect={(searchKey) => loadTableData(searchKey)} placeholder="名称/简码查询" />
					<Radio.Group style={{ marginLeft: 10 }} options={options} onChange={handleChangeRadio} value={radioValue} optionType="button" />
				</div>
				{
					// isDisplayTable ?
					<div className={'tester-table-container'}>
						<Table
							showHeader={true}
							size="small"
							rowSelection={rowSelection}
							pagination={false}
							columns={columns}
							rowKey={record => record.id}
							dataSource={productList}
						/>
					</div>

					// : (<div className="result-box">
					//   <div className="selected-item">
					//     你选择的项目如下：
					// 		{
					//       sourceProductList.filter(item => selectedRowKeys.includes(item.id)).map(item => <p>{item.name}: {item.marketPrice}</p>)
					//     }
					//   </div>
					//   <div className="test-result">
					// 		测试结果：
					// 		<p>{testResult && testResult.standard || "不达标"}</p>
					// 		<p>{testResult && testResult.level}</p>
					// 		<p>{testResult && testResult.result}</p>
					// 		<Button type="primary" onClick={() => setIsDisplayTable(true)}>好</Button>
					// 	</div>
					// </div>)
				}

				<div className="footer">
					<div className="selected-total">
						<p>
							共选中 <b>{selectedRowKeys.length}</b> 项
						</p>
						<p>
							<span>固定成本价: <b>{totalPrice && totalPrice.fixedCostPriceTotal || 0}</b>元</span>
						</p>
						<p>
							<span>可变成本价: <b>{totalPrice && totalPrice.volatileCostPriceTotal || 0}</b>元</span>
						</p>
						<p>
							<span>其他成本价: <b>{totalPrice && totalPrice.otherCostPriceTotal || 0}</b>元</span>
						</p>
						<p>
							<span>市场价: <b>{totalPrice && totalPrice.marketPriceTotal || 0}</b>元</span>
						</p>
					</div>
					<div className={'deal-content-info'}>
						必须选择项目和输入有效的成交价格才能提交评估
					</div>
					<div className="deal-content">
						<span>成交价：</span>
						<Input
							min={1}
							placeholder="请输入成交价"
							value={dealPrice}
							{
							...{ prefix: "￥", suffix: "元" }
							}
							onChange={(e) => setDealPrice(e.target.value)}
							style={{ width: 150, marginRight: 10 }} />
						<Button disabled={!isCanSubmit} type="primary" onClick={onSubmit}><SendOutlined />提交评估</Button>
					</div>
					{/* {
            testResult &&
            <div className="test-result">
              <span>评价等级: {testResult && testResult.level}</span>
              <span>评价分数: {testResult && testResult.result}</span>
              <span>是否达标: {testResult && testResult.standard || "不达标"}</span>
            </div>
          } */}
				</div>
			</div>
		</Drawer>
	)
}

export default TestDrawer
